package org.ishequ.service;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import android.content.Context;
import android.os.Environment;


public class FileService {
	
	private Context context;
	
	public FileService(Context context){
		this.context = context;
	}
	
	/**
	 * 保存文件到手机
	 * @param filename
	 * @param content
	 * @param mode 保存模式 私有、追加、读、写
	 * @throws Exception
	 */
	public void writeToLocal(String filename, String content, int mode) throws Exception {
		FileOutputStream out = context.openFileOutput(filename,mode);
		out.write(content.getBytes());
		out.close();
	}
	
	/**
	 * 保存文件到SDCard
	 * @param filename
	 * @param content
	 * @throws Exception
	 */
	public void writeToSDCard(String filename, String content) throws Exception{
		File file = new File(Environment.getExternalStorageDirectory(),filename);
		FileOutputStream out = new FileOutputStream(file);
		out.write(content.getBytes());
		out.close();
	}
	
	/**
	 * 读取私有数据
	 * @param filename
	 * @return
	 * @throws Exception
	 */
	public String readFile(String filename) throws Exception{
		FileInputStream in = context.openFileInput(filename);
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len=0;
		while((len = in.read(buffer)) != -1){
			out.write(buffer, 0, len);
		}
		byte[] data = out.toByteArray();
		return new String(data);
	}

}
